#!/bin/bash
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

if [ $# -lt 2 ]; then
  echo "usage: $(basename $0) <build> <board> ..." >&2
  echo "Example:" >&2
  echo "    $(basename $0) R24-3052.0.0 lumpy lucas" >&2
  exit 1
fi

set -e

cd ~chromeos-test/images/servo-images

# Determine the URL for the source image in googlestorage.
#   arg 1: Name of build (e.g. "R24-3052.0.0")
#   arg 2: Name of board (e.g. "lumpy")
#   output:  URL of the image for gsutil
select_source_url() {
  local build="$1"
  local board="$2"

  # Older builds keep a collection of files in a ZIP archive named
  # "image.zip".  More recent builds also have an archive named
  # "chromiumos_test_image.zip" with just the test image in it.  The
  # individual test image ZIP archive is smaller, so we prefer that
  # one when we have a choice.
  #
  local url_base="gs://chromeos-image-archive/$board-release/$build"
  local url_fullzip="$url_base/image.zip"
  local url_singlezip="$url_base/chromiumos_test_image.zip"

  if gsutil getacl "$url_singlezip" >/dev/null 2>&1; then
    echo "$url_singlezip"
  else
    echo "$url_fullzip"
  fi
}

# Deploy a single image for a single board.
#   arg 1: Name of build (e.g. "R24-3052.0.0")
#   arg 2: Name of board (e.g. "lumpy")
deploy_image() {
  local build="$1"
  local board="$2"

  local image_dir="$build-$board"
  local deployed_image="${board}_test_image.bin"

  local old_image
  if [ -h "$deployed_image" ]; then
    old_image=$(readlink "$deployed_image")
  fi

  local url=$(select_source_url "$build" "$board")
  local zip="$image_dir/image.zip"
  local bin=chromiumos_test_image.bin

  mkdir -p "$image_dir"
  gsutil cp "$url" "$zip"
  unzip -o -d "$image_dir" "$zip" "$bin"
  ln -sf "$image_dir/$bin" "$deployed_image"
  rm -f "$zip"

  if [ -n "$old_image" ]; then
    local digits='[0-9][0-9]*'
    local pattern="\(R$digits-$digits\.$digits\.$digits-[^/][^/]*\)/..*"
    old_image_dir=$(expr "$old_image" : "$pattern" || true)
    if [ -z "$old_image_dir" ]; then
      echo  >&2
      echo "Warning:  Previous image $old_image wasn't created" >&2
      echo "Warning:  by this script.  You need to manually remove the" >&2
      echo "Warning:  obsolete image and any associated .zip files." >&2
      echo  >&2
    elif [ -d "$old_image_dir" -a "$old_image_dir" != "$image_dir" ]; then
      echo "Cleaning up $old_image_dir" >&2
      rm -rf "$old_image_dir"
    fi
  fi
}

BUILD="$1"
shift

for BOARD in "$@"; do
  deploy_image "$BUILD" "$BOARD"
done
